package com.cyy.operation.appium;

import io.appium.java_client.android.AndroidDriver;
import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.springframework.stereotype.Component;

import java.net.MalformedURLException;
import java.net.URL;

@Slf4j
@Component
public class AndroidAppium extends AbstractAppium {

    /**
     * 创建驱动
     *
     * @param deviceName      设备的名字,ip:port
     * @param platformVersion 执行机的版本号,eg: 4.4.2
     * @param appPackage      测试应用的包名
     * @param appActivity     测试应用的入口
     * @param appiumIP        appium服务的ip，eg:127.0.0.1
     * @param appiumPORT      appium服务的port
     * @return driver
     * @throws MalformedURLException
     */
    public AndroidDriver installDriver(String deviceName, String platformVersion, String appPackage, String appActivity,
                                       String appiumIP, int appiumPORT)
            throws MalformedURLException {
        // 1.配置
        DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
        //指定测试设备的名称
        desiredCapabilities.setCapability("deviceName", deviceName);
        //添加操作系统配置
        desiredCapabilities.setCapability("platformName", "Android");
        //添加操作系统版本设置
        desiredCapabilities.setCapability("platformVersion", platformVersion);
        //指定想要测试应用的包名
        desiredCapabilities.setCapability("appPackage", appPackage);
        //指定想要测试应用的入口activity
        desiredCapabilities.setCapability("appActivity", appActivity);
        desiredCapabilities.setCapability("autoGrantPermissions", true);
//        String udid = String.format("%s:%s", System.getenv("Ip"), System.getProperty("Port"));
//        desiredCapabilities.setCapability("udid", udid);
        desiredCapabilities.setCapability("unicodeKeyboard", true); // 设置app可以输入中文字符
        desiredCapabilities.setCapability("noReset", false);
        //2.创建驱动...URL是appium的固定地址；指定appium通讯的地址，将相对应的配置传入到驱动里边
        String appiumURL = String.format("http://%s:%d/wd/hub", appiumIP, appiumPORT);
        log.warn("新建驱动地址:" + appiumURL);
        AndroidDriver androidDriver = new AndroidDriver(new URL(appiumURL), desiredCapabilities);

        return androidDriver;

    }

    public AndroidDriver installDriver(String deviceName, String platformVersion, String appPackage, String appActivity)
            throws MalformedURLException {
        return installDriver(deviceName, platformVersion, appPackage, appActivity, "localhost", 4723);
    }

}
